package com.steakliu.sun.registry.api;

import com.steakliu.sun.common.meta.ServiceMeta;
import com.steakliu.sun.common.util.RandomUtil;
import com.steakliu.sun.loadbalancer.api.LoadBalancer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能说明： 扩展器
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-11  22:26
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class RegistryServiceExtender {

    /**
     * 获取目标服务
     * @param directConnections
     * @param serviceMetaList
     * @param loadBalancer
     * @return
     */
    protected ServiceMeta getTargetService(String directConnections, List<ServiceMeta> serviceMetaList, LoadBalancer loadBalancer) {
        //先从缓存中获取
        if (null != serviceMetaList && serviceMetaList.size() > 0){
            List<ServiceMeta> metaList = this.selectTagerServiceMetaList(directConnections, serviceMetaList);
            return loadBalancer.select(metaList);
        }
        return null;
    }

    /**
     * 选出目标服务集
     * @param directConnections
     * @param serviceMetas
     * @return
     */
    private List<ServiceMeta> selectTagerServiceMetaList(String directConnections, List<ServiceMeta> serviceMetas){
        if (null == directConnections || directConnections.isEmpty()){
            return null;
        }
        ArrayList<ServiceMeta> metas = new ArrayList<>();
        String[] connectAddress = directConnections.split(",");
        for (String address : connectAddress) {
            for (ServiceMeta meta : serviceMetas) {
                String[] hostAndPort = address.split(":");
                String host = hostAndPort[0].trim();
                int port = Integer.parseInt(hostAndPort[1].trim());
                if (meta.getHost().equals(host) && meta.getPort() == port){
                    metas.add(meta);
                }
            }
        }
        return metas;
    }


}
